import Vue from "vue";

function Utils() {
  // 获取当前时间
  this.$getDate = (n) => {
    let t = n ? parseInt(n) : "";
    let date = new Date(t || Date.now());
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = month < 10 ? "0" + month : month;

    let day = date.getDate();
    day = day < 10 ? "0" + day : day;

    let hour = date.getHours();
    hour = hour < 10 ? "0" + hour : hour;

    let minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;

    let second = date.getSeconds();
    second = second < 10 ? "0" + second : second;

    let timestamp = date.getTime();
    let week = date.getDay();

    let weekValue = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    return {
      year,
      month,
      day,
      hour,
      minute,
      second,
      timestamp,
      week,
      weekValue: weekValue[week],
      dateTimeValue: `${year}年${month}月${day}日 ${hour}时${minute}分${second}`,
      dateTime: `${year}-${month}-${day} ${hour}:${minute}:${second}`,
    };
  };
  // 获取格式化时间
  this.$formatDate = (d, type = 1) => {
    let date = this.$getDate(d);
    if (type == 1) {
      return `${date.year}年${date.month}月${date.day}日 ${date.hour}时${date.minute}分${date.second}`;
    } else {
      return `${date.year}-${date.month}-${date.day} ${date.hour}:${date.minute}:${date.second}`;
    }
  };

  // 判断是否为空
  this.$notEmpty = (value) => {
    switch (typeof value) {
      case "undefined":
        return false;
      case "string":
        if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, "").length == 0)
          return false;
    }
    return true;
  };

  // 格式化手机号,吧中间四位替换成*号
  this.$formatPhone = (value) => {
    value = value ? value + "" : "";
    if (!value) return "";
    let reg = /^(\d{3})\d{4}(\d{4})$/;
    return value.replace(reg, "$1****$2");
  };
}

let utils = new Utils();
for (let key in utils) {
  Vue.prototype[key] = utils[key];
}
